//
//  WKSingleViewController.m
//  Walk
//
//  Created by cesh on 16/9/2.
//  Copyright © 2016年 cesh. All rights reserved.
//

#import "WKSingleViewController.h"
#import "WKMultipleViewController.h"
#import "WKCardViewController.h"
#import "WKReportViewController.h"
#import <Masonry.h>

@interface WKSingleViewController () <UIScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource>

//毛玻璃
@property (strong, nonatomic) UIToolbar *glassBG;

@property (weak, nonatomic) IBOutlet UIImageView *backImg;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;

@property (weak, nonatomic) IBOutlet UIView *activeDegreeView;
//用户资料
@property (copy, nonatomic) NSString *user_id;

@property (weak, nonatomic) IBOutlet UILabel *name;
@property (weak, nonatomic) IBOutlet UILabel *genderAge;
@property (weak, nonatomic) IBOutlet UILabel *descriptionLbl;
@property (weak, nonatomic) IBOutlet UILabel *school;
@property (weak, nonatomic) IBOutlet UILabel *major;
//活动热度
@property (weak, nonatomic) IBOutlet UILabel *serial_login;
@property (weak, nonatomic) IBOutlet UILabel *join_event;
@property (weak, nonatomic) IBOutlet UILabel *finish_event;
@property (weak, nonatomic) IBOutlet UILabel *fav_event;


@property (strong, nonatomic) NSMutableArray *images;

@property (weak, nonatomic) IBOutlet UIImageView *moreImg;

@property (strong, nonatomic) NSArray *activeInfo;
@end

@implementation WKSingleViewController

- (NSMutableArray *)images {
    if (_images == nil) {
        _images = [NSMutableArray array];
    }
    return _images;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //给左上角的返回添加事件
    self.backImg.userInteractionEnabled = YES;
    [self.backImg addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapOnBack)]];
    self.pageControl.numberOfPages = self.images.count;
    
    self.scrollView.alpha = 0;
    
    self.moreImg.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(moreHandle)];
    [self.moreImg addGestureRecognizer:tap];
}

- (void)moreHandle {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更多操作" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *share = [UIAlertAction actionWithTitle:@"分享" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        WKPopView *popView = [WKPopView showWithType:PopViewTypeJustBlur];
        UIView *sharePopView = [[[NSBundle mainBundle]loadNibNamed:@"WKSharePopView" owner:nil options:nil]lastObject];
        sharePopView.center = CGPointMake(screenW * 0.5, screenH * 0.5);
        [popView addSubview:sharePopView];
    }];
    
    UIAlertAction *report = [UIAlertAction actionWithTitle:@"举报" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        //弹出举报界面
        WKReportViewController *reportVC = [[WKReportViewController alloc]init];
        reportVC.reportType = ReportTypeUser;
        reportVC.user_id = self.user_id;
        [self presentViewController:reportVC animated:YES completion:nil]; ;
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:share];
    [alert addAction:report];
    [alert addAction:cancel];
    
    [self presentViewController:alert animated:YES completion:nil];
}



//这时候才能取得正确的scrollView的frame
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self setupScrollView];
}

- (void)tapOnBack {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)setupScrollView {
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.bounces = NO;
    self.scrollView.contentSize = CGSizeMake(_images.count * screenW, 0);
    [UIView animateWithDuration:1.0 animations:^{
        self.scrollView.alpha = 1;
        for (NSInteger i = 0; i < _images.count; i++) {
            UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(i * screenW, 0, screenW, self.scrollView.height)];
            imgV.contentMode = UIViewContentModeScaleToFill;
            
            imgV.image = [UIImage imageNamed:@"default_head"];
            
            [imgV sd_setImageWithURL:_images[i] placeholderImage:[UIImage imageNamed:@"default_head"]];
            
            [self.scrollView addSubview:imgV];
        }
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    self.pageControl.currentPage = scrollView.contentOffset.x / screenW;
}

- (IBAction)noBtn:(id)sender {
    //如果是从多人界面进入的本界面
    if (self.isSuperMultiple) {
        [self dismissViewControllerAnimated:NO completion:^{
            //多人界面点击NO
            [self.multipleVC dismissViewControllerAnimated:NO completion:^{
                [self.cardVC dislike];
            }];
        }];
    }
    //如果是从卡片界面进入的本界面
    else {
        [self dismissViewControllerAnimated:NO completion:^{
            //卡片界面点击NO
            [self.cardVC dislike];
        }];
    }
}
- (IBAction)yesBtn:(id)sender {
    //如果是从多人界面进入的本界面
    if (self.isSuperMultiple) {
        [self dismissViewControllerAnimated:NO completion:^{
            //多人界面点击YES
            [self.multipleVC dismissViewControllerAnimated:NO completion:^{
                [self.cardVC like];
            }];
        }];
    }
    //如果是从卡片界面进入的本界面
    else {
        [self dismissViewControllerAnimated:NO completion:^{
            //卡片界面点击YES
            [self.cardVC like];
        }];
    }
}

- (IBAction)detailBtn:(id)sender {
    [self setupBlur];
    //在毛玻璃上添加控件
    //活跃度
    UIButton * activeBtn = [[UIButton alloc]init];
    [activeBtn setImage:[UIImage imageNamed:@"active_black"] forState:UIControlStateNormal];
    [activeBtn setTitle:@"活跃度" forState:UIControlStateNormal];
    [activeBtn setTitleColor:[UIColor colorWithRed:0x4a / 255.0 green:0x4a / 255.0 blue:0x4a / 255.0 alpha:1.0] forState:UIControlStateNormal];
    [activeBtn.titleLabel setFont:[UIFont systemFontOfSize:14.0]];
    activeBtn.userInteractionEnabled = NO;
    activeBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -6, 0, 0);
    [activeBtn sizeToFit];
    activeBtn.center = CGPointMake(screenW * 0.5, 30 + activeBtn.height * 0.5);
    [self.glassBG addSubview:activeBtn];
    
    //横条
    UIView *grayBar = [[UIView alloc]initWithFrame:CGRectMake(10, activeBtn.bottom + 4, screenW - 20, 0.5)];
    grayBar.backgroundColor = [UIColor colorWithRed:0x4a / 255.0 green:0x4a / 255.0 blue:0x4a / 255.0 alpha:1.0];
    [self.glassBG addSubview:grayBar];
    
    //下方的X按钮
    UIButton *cancelBtn = [[UIButton alloc]init];
    [cancelBtn setImage:[UIImage imageNamed:@"no_glass"] forState:UIControlStateNormal];
    [cancelBtn sizeToFit];
    cancelBtn.center = CGPointMake(screenW * 0.5, screenH - cancelBtn.height * 0.5 - 34);
    [cancelBtn addTarget:self action:@selector(dismissGlass) forControlEvents:UIControlEventTouchUpInside];
    [self.glassBG addSubview:cancelBtn];
    //各类活动参与次数的collectionView
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 行间距
    flowLayout.minimumLineSpacing = 25;
    // 每个item 之间的间距
    flowLayout.minimumInteritemSpacing = 20;
    
    // 设置每个cell 的尺寸
    flowLayout.itemSize = CGSizeMake(75, 60);
    
    // 设置滚动方向 水平滚动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    UICollectionView *collectionV = [[UICollectionView alloc]initWithFrame:CGRectMake(25, grayBar.bottom + 20, screenW - 25 * 2, cancelBtn.top - grayBar.bottom) collectionViewLayout:flowLayout];
    collectionV.dataSource = self;
    collectionV.delegate = self;
    collectionV.backgroundColor = [UIColor clearColor];
    [collectionV registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    collectionV.showsVerticalScrollIndicator = NO;
    [self.glassBG addSubview:collectionV];
}

//设置数据
- (void)setData:(NSDictionary *)data {

    _data = data;
    
    self.user_id = data[@"id"];
    
    NSString *name = [NSString stringWithFormat:@"%@", data[@"nickname"]];
    self.name.text = name;
    NSString *gender = [[NSString stringWithFormat:@"%@", data[@"sex"]] isEqualToString:@"1"] ? @"男" : @"女";
    NSString *birthday = [NSString stringWithFormat:@"%@", data[@"birthday"]];
    NSInteger age = ([[NSDate date] timeIntervalSince1970] - [birthday integerValue]) / (365 * 24 * 3600);
    
    self.genderAge.text = [NSString stringWithFormat:@"%@ %li", gender, (long)age];
    
    NSString *describe = [NSString stringWithFormat:@"%@", data[@"describe"]];
    self.descriptionLbl.text = [describe length] == 0 ? @"我就是我，是不一样的烟火，只为自己带盐。我是蛙客，拒绝独行！" : describe;
    
    NSString *school = [NSString stringWithFormat:@"%@", data[@"school"][@"name"]];
    self.school.text = school;
    
    NSString *major = [NSString stringWithFormat:@"%@", data[@"major"][@"title"]];
    self.major.text = major;
    
    NSString *serial_login = [NSString stringWithFormat:@"%@", data[@"active"][@"serial_login"]];
    self.serial_login.text = serial_login;
    
    NSString *join_event = [NSString stringWithFormat:@"%@", data[@"active"][@"jion_event"]];
    self.join_event.text = join_event;
    
    NSString *finish_event = [NSString stringWithFormat:@"%@", data[@"active"][@"finsh_event"]];
    self.finish_event.text = finish_event;
    
    NSString *fav_event = [NSString stringWithFormat:@"%@", data[@"active"][@"best_event"]];
    self.fav_event.text = fav_event;
    
    NSString *headerImgURL = data[@"headerImg"][@"url"];
    if (headerImgURL) {
        [self.images addObject:headerImgURL];
    }
    
    NSArray *otherImg = data[@"otherImg"];
    for (NSInteger i = 0; i < otherImg.count; i++) {
        NSString *otherImgUrl = data[@"otherImg"][i][@"url"];
        [self.images addObject:otherImgUrl];
    }
    
    self.pageControl.numberOfPages = self.images.count;
    
    NSArray *activeInfo = data[@"activeInfo"];
    self.activeInfo = activeInfo;
}


//collectionView相关方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.activeInfo.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[UICollectionViewCell alloc]init];
    }
    
    cell.backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 75, 60)];
    
    //添加活动图标
    UIImageView *icon = [[UIImageView alloc]init];    
    icon.image = [UIImage imageNamed:@"default_head"];
    [icon sd_setImageWithURL:self.activeInfo[indexPath.row][@"img"] placeholderImage:[UIImage imageNamed:@"default_head"]];
    
    icon.size = CGSizeMake(40, 30);
    icon.center = CGPointMake(cell.backgroundView.width * 0.5, icon.height * 0.5);
    [cell.backgroundView addSubview:icon];
    
    //添加参加次数
    UILabel *name = [[UILabel alloc]init];
    
    NSString *times = self.activeInfo[indexPath.row][@"times"];
    NSString *activity = self.activeInfo[indexPath.row][@"type"];
    
    NSMutableAttributedString *aAttributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@次",activity, times]];
    //富文本样式
    [aAttributedString addAttribute:NSForegroundColorAttributeName  //文字颜色
                                          value:[UIColor colorWithRed:0x4a / 255.0 green:0x4a / 255.0 blue:0x4a / 255.0 alpha:1.0]
                                           range:NSMakeRange(0, aAttributedString.length)];
    [aAttributedString addAttribute:NSFontAttributeName             //文字字体
                                         value:[UIFont systemFontOfSize:12]
                                        range:NSMakeRange(0, aAttributedString.length - 2)];
    
    [aAttributedString addAttribute:NSFontAttributeName             //文字字体
                                  value:[UIFont systemFontOfSize:20]
                                  range:NSMakeRange(aAttributedString.length - 1 - [times length],[times length])];


    [aAttributedString addAttribute:NSFontAttributeName             //文字字体
                              value:[UIFont systemFontOfSize:12]
                              range:NSMakeRange(aAttributedString.length - 1, 1)];
    
    name.attributedText = aAttributedString;
    [name sizeToFit];
    name.center = CGPointMake(cell.backgroundView.width * 0.5, cell.height - name.height * 0.5);
    [cell.backgroundView addSubview:name];
    
    return cell;
}


//退出毛玻璃
- (void)dismissGlass {
    
    [UIView animateWithDuration:0.5 animations:^{
        self.glassBG.alpha = 0.01;
    } completion:^(BOOL finished) {
        [self.glassBG removeFromSuperview];
    }];
    
}
#pragma mark - 添加毛玻璃
- (void)setupBlur {
    
    // 1.创建toolBar
    UIToolbar *toolBar = [[UIToolbar alloc] init];
    toolBar.alpha = 0;
    [self.view addSubview:toolBar];
    
    // 1.1改变样式
    toolBar.barStyle = UIBarStyleDefault;
    toolBar.translucent = YES;
    
    // 2.添加约束
    [toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    
    [UIView animateWithDuration:0.5 animations:^{
        toolBar.alpha = 1.0;
    }];
    self.glassBG = toolBar;
}

@end
